package com.ztesoft.book.admin.filter;

import com.google.common.collect.Lists;
import org.springframework.boot.SpringBootConfiguration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lzq.
 * @description
 * @date 2021-07-26 17:26
 */
@SpringBootConfiguration
@WebFilter(filterName = "XssFilter", urlPatterns = "/*")
public class XssFilter implements Filter {

    /**
     * 无需进行xss过滤的uri地址
     */
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList("/login", "/upload")));

    /**
     * 无需进行xss过滤的uri地址
     */
    private static final Set<String> ALLOWED_IMPORT_PATHS = Collections.unmodifiableSet(
            new HashSet<>(Lists.newArrayList("/goods/goods/import")));


    @Override
    public void init(FilterConfig filterConfig) {
        // TODO Auto-generated method stub
    }

    /**
     * doFilter
     *
     * @param req   req
     * @param resp  resp
     * @param chain chain
     * @throws IOException      IOException
     * @throws ServletException ServletException
     */
    @Override
    public void doFilter(
            ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String path = request.getRequestURI()
                .substring(request.getContextPath()
                        .length())
                .replaceAll("[/]+$", "");

        boolean allowedPath = ALLOWED_PATHS.contains(path);

        if (allowedPath) {
            chain.doFilter(request, response);
        }
        else {
            if (ALLOWED_IMPORT_PATHS.contains(path)) {
                chain.doFilter(request, response);
            }
            else {
                chain.doFilter(new XssHttpServletRequestWrapper(request), response);
            }
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}
